package com.tanhua.system.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.system.mapper.FreezingMapper;
import com.tanhua.system.mapper.LoggingMapper;
import com.tanhua.system.mapper.UserInfoMapper;
import com.tanhua.system.mapper.UserMapper;
import com.tanhua.system.pojo.Freezing;
import com.tanhua.system.pojo.Logging;
import com.tanhua.system.pojo.User;
import com.tanhua.system.pojo.UserInfo;
import com.tanhua.system.vo.PageResult;
import com.tanhua.system.vo.UserDataVo;
import com.tanhua.system.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FreezingMapper freezingMapper;

    @Autowired
    private LoggingMapper loggingMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 通过sso的rest接口查询
     */
    public com.tanhua.system.pojo.User queryUserByToken(String token) {
        String url = ssoUrl + "/user/" + token;
        try {
            String data = restTemplate.getForObject(url, String.class);
            //如果返回的是空,说明查询出错了即返回空
            if (StringUtils.isEmpty(data)) {
                return null;
            }
            return MAPPER.readValue(data, User.class);
        } catch (IOException e) {
            log.error("校验token出错，token = " + token, e);
        }
        return null;
    }

    /**
     * 模糊分页查询
     *
     * @param page
     * @param pagesize
     * @param id
     * @param nickname
     * @param city
     * @return
     */
    public PageResult queryUserData(Integer page, Integer pagesize, String id, String nickname, String city) {

        try {
            PageResult pageResult = new PageResult();
            pageResult.setCounts(0);
            pageResult.setPagesize(pagesize);
            pageResult.setPages(0);
            pageResult.setPage(page);

            //根据传入的id、昵称、城市进行模糊判断
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(StringUtils.isNotEmpty(id), "user_id", id);
            queryWrapper.like(StringUtils.isNotEmpty(nickname), "nick_name", nickname);
            queryWrapper.like(StringUtils.isNotEmpty(city), "city", city);

            IPage<UserInfo> userInfoIPage = this.userInfoMapper.selectPage(new Page<>(page, pagesize), queryWrapper);

            List<UserDataVo> userDataVos = new ArrayList<>();
            for (UserInfo userInfo : userInfoIPage.getRecords()) {
                UserDataVo userDataVo = new UserDataVo();
                userDataVo.setId(userInfo.getUserId());
                userDataVo.setLogo(userInfo.getLogo());
                userDataVo.setNickname(userInfo.getNickName());
                userDataVo.setSex(userInfo.getSex() == "1" ? "男" : "女");//性别 man woman todo
                userDataVo.setAge(userInfo.getAge());
                userDataVo.setUserStatus(userInfo.getState());
                userDataVo.setCity(userInfo.getCity());
                userDataVo.setLastActiveTime(null);//最近活跃时间 todo
                userDataVos.add(userDataVo);
            }

            pageResult.setItems(userDataVos);

            return pageResult;
        } catch (Exception e) {
            log.error("查询失败~", e);
        }
        return null;
    }

    /**
     * 查询用户基本资料
     *
     * @param userId
     * @return
     */
    public UserInfoVo queryUserInfoById(Long userId) {
        if (null == userId) {
            return null;
        }
        UserInfoVo userInfoVo = new UserInfoVo();

        UserInfo userInfo = this.userInfoMapper.selectById(userId);
        if (userInfo == null) {
            return null;
        } else {//用户信息不等于null就添加信息
            userInfoVo.setId(userInfo.getUserId());
            userInfoVo.setNickname(userInfo.getNickName());//昵称
            userInfoVo.setSex(userInfo.getSex() == "1" ? "男" : "女");//性别 man woman todo
            userInfoVo.setAge(userInfo.getAge());//年龄
            userInfoVo.setIncome(Integer.valueOf(userInfo.getIncome()));//月收入
            userInfoVo.setLogo(userInfo.getLogo());//头像
            userInfoVo.setOccupation(userInfo.getIndustry());
            userInfoVo.setTags(userInfo.getTags());
            userInfoVo.setPersonalSignature(userInfo.getPersonalSignature());//个性签名
            userInfoVo.setUserStatus(userInfo.getState());//用户状态，1为正常，2为冻结
        }
        QueryWrapper<User> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq("id", userId);
        User user = this.userMapper.selectOne(wrapperUser);
        userInfoVo.setCreated(user.getCreated());//注册时间
        userInfoVo.setMobile(user.getMobile());//手机号，即用户账号
        userInfoVo.setUserStatus(userInfo.getState());

        Long eachLikeCount = this.userLikeApi.queryEachLikeCount(userId);
        userInfoVo.setCountMatching(eachLikeCount);//配对人数
        Long likeCount = this.userLikeApi.queryLikeCount(userId);
        userInfoVo.setCountLiked(likeCount);//喜欢人数
        Long fanCount = this.userLikeApi.queryFanCount(userId);
        userInfoVo.setCountBeLiked(fanCount);//被喜欢人数

//        private String city; //注册地区 todo
        QueryWrapper<Logging> wrapperLogging = new QueryWrapper<>();
        wrapperLogging.eq("user_id", userId);
        Logging logging = this.loggingMapper.selectOne(wrapperLogging);
        userInfoVo.setLastActiveTime(logging.getLogin());//最近活跃时间 todo
        userInfoVo.setLastLoginLocation(logging.getLastLocation());//最近登录地 todo

        return userInfoVo;
    }

    /**
     * 用户状态：冻结
     *
     * @param freezing
     * @return
     */
    public Boolean freeze(Freezing freezing) {
        //根据id查询该到该用户
        QueryWrapper<Freezing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", freezing.getUserId());
        Freezing freeze = this.freezingMapper.selectOne(queryWrapper);

        //根据id查出用户，并将用户状态设置为冻结
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserInfo::getUserId, freezing.getUserId()).set(UserInfo::getState, "2");
        this.userInfoMapper.update(null, lambdaUpdateWrapper);

        //将用户冻结信息添加到冻结表里
        if (null == freeze) {
            //不存在就将信息插入
            return this.freezingMapper.insert(freezing) > 0;
        } else {
            //存在就将信息进行更改
            return this.freezingMapper.update(freezing, queryWrapper) > 0;
        }

    }

    /**
     * 用户状态：解冻
     *
     * @param freezing
     * @return
     */
    public Boolean unFreeze(Freezing freezing) {

        //根据id查询该到该用户
        QueryWrapper<Freezing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", freezing.getUserId());
        Freezing freeze = this.freezingMapper.selectOne(queryWrapper);

        //根据id查出用户，并将用户状态设置为解冻
        LambdaUpdateWrapper<UserInfo> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(UserInfo::getUserId, freezing.getUserId()).set(UserInfo::getState, "1");
        this.userInfoMapper.update(null, lambdaUpdateWrapper);

        //将用户冻结信息添加到表里
        if (null == freeze) {
            return true;
        } else {
            //存在就将信息进行更改
            return this.freezingMapper.update(freezing, queryWrapper) > 0;
        }

    }

    /**
     * 新增用户
     * @param thisYearTimeList
     * @param lastYearTimeList
     * @return
     */
    public List<Integer> saveUser(List<Long> thisYearTimeList, List<Long> lastYearTimeList) {
        List<Integer> list = new ArrayList<>();
        //遍历集合开始找到这个时间段的所有用户
        for (int i = 0; i < thisYearTimeList.size() - 1; i++) {
            LambdaQueryWrapper<User> thisYearQueryWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<User> lastYearQueryWrapper = new LambdaQueryWrapper<>();
            thisYearQueryWrapper.ge(User::getCreated, new Date(lastYearTimeList.get(i))).lt(User::getCreated, new Date(lastYearTimeList.get(i + 1)));
            lastYearQueryWrapper.ge(User::getCreated, new Date(thisYearTimeList.get(i))).lt(User::getCreated, new Date(thisYearTimeList.get(i + 1)));
            Integer thisYearCount = this.userMapper.selectCount(thisYearQueryWrapper);
            Integer lastYearCount = this.userMapper.selectCount(lastYearQueryWrapper);
            list.add(thisYearCount);
            list.add(lastYearCount);
        }
        return list;
    }

    public List<List<Long>> queryNextDay(List<Long> thisYearTimeList, List<Long> lastYearTimeList) {

        List<List<Long>> nextList = new ArrayList<>();
        //查询时间
        for (int i = 0; i < thisYearTimeList.size() - 1; i++) {
            LambdaQueryWrapper<User> thisYearWrapper = new LambdaQueryWrapper<>();
            LambdaQueryWrapper<User> lastYearWrapper = new LambdaQueryWrapper<>();
            thisYearWrapper.between(User::getId, new Date(thisYearTimeList.get(i) - 24 * 3600000), new Date(thisYearTimeList.get(i + 1) - 24 * 3600000));
            lastYearWrapper.between(User::getId, new Date(lastYearTimeList.get(i) - 24 * 3600000), new Date(lastYearTimeList.get(i + 1) - 24 * 3600000));

            List<User> thisYearUserList = this.userMapper.selectList(thisYearWrapper);
            List<User> lastYearUserList = this.userMapper.selectList(lastYearWrapper);


            List<Long> thisYearUserIds = new ArrayList<>();
            for (User user : thisYearUserList) {
                thisYearUserIds.add(user.getId());
            }
            List<Long> lastYearUserIds = new ArrayList<>();
            for (User user : lastYearUserList) {
                lastYearUserIds.add(user.getId());
            }
            //添加进集合
            nextList.add(thisYearUserIds);
            nextList.add(lastYearUserIds);

        }
        return nextList;
    }
}
